package com.agileai.esb.smc.controller.sysres;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.esb.smc.bizmoduler.sysres.SysUserManage;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.StandardEditHandler;
import com.agileai.hotweb.domain.FormSelectFactory;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.RedirectRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.util.CryptionUtil;
import com.agileai.util.MapUtil;

public class SysUserManageEditHandler
        extends StandardEditHandler {
    public SysUserManageEditHandler() {
        super();
        this.listHandlerClass = SysUserManageListHandler.class;
        this.serviceId = buildServiceId(SysUserManage.class);
    }

	public ViewRenderer doSaveAction(DataParam param){
		String operateType = param.get(OperaType.KEY);
		if (OperaType.CREATE.equals(operateType)){
			String userPassword = param.get("USER_PWD");
			String encodePassword = CryptionUtil.md5Hex(userPassword);
			param.put("USER_PWD",encodePassword);
			getService().createRecord(param);	
		}
		else if (OperaType.UPDATE.equals(operateType)){
			getService().updateRecord(param);	
		}
		return new RedirectRenderer(getHandlerURL(listHandlerClass));
	}    
    
    protected void processPageAttributes(DataParam param) {
        setAttribute("USER_TYPE",
                     FormSelectFactory.create("UserType")
                                      .addSelectedValue(getOperaAttributeValue("USER_TYPE",
                                                                               "developer")));
        setAttribute("USER_STATE",
                     FormSelectFactory.create("UserState")
                                      .addSelectedValue(getOperaAttributeValue("USER_STATE",
                                                                               "enable")));
    }
    
    @PageAction
    public ViewRenderer isExistUser(DataParam param){
    	String responseText = "false";
    	DataRow row = getService().getRecordByCode(param);
    	if (!MapUtil.isNullOrEmpty(row)){
    		responseText = "true";
    	}
    	return new AjaxRenderer(responseText);
    }
    protected SysUserManage getService() {
        return (SysUserManage) this.lookupService(this.getServiceId());
    }
}
